package cn.zhqr.common.util.tree;


import cn.zhqr.common.util.collections.Lists;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 树状接口生成工具类
 * Created by yantingjun on 2017/12/8.
 */
public class TreeNodeKit {
    public static List<TreeNode> toTree(List<? extends  INode> nodeList){
        List nodes = null;
        if (nodeList!=null && nodeList.size() > 0) {
            //优先级排序
            Collections.sort(nodeList, new Comparator<INode>() {
                @Override
                public int compare(INode rp1, INode rp2) {
                    return rp1.getPid().compareTo(rp2.getPid());
                }
            });
            nodes = toTree(nodeList, nodeList.get(0).getPid());
        }
        return nodes;
    }

    /**
     * 无限级树形结构
     *
     * @param params params
     * @param pid    pid
     * @return list
     */
    public static List toTree(List params, long pid) {
        List nodes = Lists.arrayList();

        if (params != null && params.size() > 0) {

            TreeNode node = null;
            for (int i = 0; i < params.size(); i++) {
                node = (TreeNode)params.get(i);
                if (node.getPid() == pid) {
                    nodes.add(node);
                    params.remove(i);
                    node.setSubNodes(toTree(params, node.getId()));
                    i--;
                }
            }
        }
        return nodes;
    }

}
